package com.sky.controller.admin.Adimin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
public class DishController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DishService dishService;
    /**
     * 新增菜品
     * */
    @PostMapping
    public Result save(@RequestBody DishDTO dishDTO){
        log.info("新增菜品，数据：{}", dishDTO);
        dishService.saveDishAndFlavor(dishDTO);
        /// 清理缓存
        redisTemplate.delete("dish"+dishDTO.getCategoryId());
        return Result.success();
    }

    /**
     * 分页查询
     * */
    @GetMapping("/page")
    public Result page(DishPageQueryDTO dishPageQueryDTO){
        log.info("分页查询 数据", dishPageQueryDTO);
        PageResult pageResult = dishService.page(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     *  根据id查询
     * */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id){
        log.info("根据id查询");
        DishVO dishVO = dishService.getById(id);
        return Result.success(dishVO);
    }

    /**
     *  根据id删除，批量删除
     * */
    @DeleteMapping
    public Result deleteById(@RequestParam(required = false) List<Long> ids){
        log.info("根据id删除id={}",ids);
        dishService.deleteById(ids);
        /// 清理缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success();
    }

    /**
     *  起售与停售
     * */
    @PostMapping("/status/{status}")
    public Result setStatus(@PathVariable Integer status,Long id){
        log.info("设置了id:{}状态为：{}",id,status);
        dishService.setStatus(status,id);
        /// 清理缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success();
    }

    /**
     *  修改菜品
     * */
    @PutMapping
    @CachePut
    public Result changeDish(@RequestBody DishDTO dishDTO){
        log.info("修改菜品");
        dishService.update(dishDTO);

        /// 清理缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success();
    }

    /**
     * 分类Id查询
     * */
    @GetMapping("/list")
    public Result<List<Dish>> getByCategoryId(Long categoryId){
        log.info("分类Id查询");
        List<Dish> categoryIdList = dishService.getByCategoryId(categoryId);
        return Result.success(categoryIdList);
    }

}
